<?php
namespace app\common\model;

use nxcsoft\wechat\Driver;

/**
 * 小程序名称模型
 */
class AppletName extends BaseModel
{
    // 定义表名
    protected $name = 'applet_name';

    // 定义主键
    protected $pk = 'applet_name_id';

    // 追加字段
    protected $append = [];

    /**
     * 状态
     */
    public function getStatusAttr($value)
    {
        $status = ['审核中', '设置成功', '被驳回'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取详情
     */
    public static function getAppletName(array $filter)
    {
        // 筛选条件
        return self::where($filter)->order('applet_name_id', 'desc')->find();
    }

    /**
     * 操作
     */
    public function action(array $data, $applet_id)
    {
        if (!isset($data['license']) || empty($data['license'])) {
            $this->error = '请选择营业执照';
            return false;
        }
        $wx = new Driver;
        //上传临时素材
        if (!$license = $wx->upTempMaterial($data['license'], $applet_id)) {
            $this->error = '营业执照上传失败';
            return false;
        }
        $other1 = '';
        if (isset($data['naming_other_stuff_1']) and !empty($data['naming_other_stuff_1'])) {
            if (!$other1 = $wx->upTempMaterial($data['naming_other_stuff_1'], $applet_id)) {
                $this->error = '补充材料上传失败';
                return false;
            }
        }
        if (!$result = $wx->setNickName($applet_id, $data['nick_name'], $license, $other1)) {
            $this->error = $wx->getError();
            return false;
        }
        $data['status'] = 1;//审核成功
        $status = '';
        if (isset($result['audit_id']) and !empty($result['audit_id'])) {
            $data['status'] = 0;//需要审核
            $data['audit_id'] = $result['audit_id'];
            $status = '-> 审核中...';
        }
        $applet = Applet::get($applet_id);
        $applet->app_name = $data['nick_name'] . $status;
        $applet->save();
        return $this->save($data);
    }
}
